<template>
	<el-upload
		class="upload-demo"
		ref="upload"
		:headers="setHeaders"
		:multiple="false"
		:action="action"
		:before-upload="beforeUpload"
		:on-preview="handlePreview"
		:on-success="handleSuccess"
		:on-error="handleError"
		:on-remove="handleRemove"
		:before-remove="beforeRemove"
		:on-change="handleChange"
		:on-exceed="handleExceed"
		:on-progress="handleProgress"
		:file-list="fileList"
		:auto-upload="autoUpload"
		:data="form"
		:accept="accept"
	>
		<el-button size="small" icon="el-icon-plus" title="请上传本地视频" type="primary">{{ buttonTxt }}</el-button>
	</el-upload>
</template>

<script>
import { getAttachUrl } from '@/api/openApi.js';
import { mapGetters } from 'vuex';
export default {
	data() {
		return {
			setHeaders: { Authorization: '' },
			fileList: [],
			fileIndex: 0,
			form: {},
			autoUpload: false,
			action: '',
			accept2: ''
		};
	},
	props: ['menuData', 'buttonTxt', 'values', 'number', 'accept', 'returnFunction', 'type', 'data', 'fileSize'],
	created() {
		this.setHeaders = { Authorization: this.token };
		let baseURL = !window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl;
		this.action = baseURL + 'tbSysAttachment/upload';
		if (this.data != undefined) {
			if (this.data.autoUpload != undefined) {
				this.autoUpload = this.data.autoUpload;
			}
		}
	},
	mounted() {
		// this.accept2=this.accept;
		// this.accept2=this.accept+","+this.accept.toUpperCase();
	},
	computed: {
		...mapGetters(['token']),
		imageUrl() {
			return this.imgUrl;
		}
	},
	methods: {
		handleAvatarSuccess(response, file, fileList) {},
		//文件上传成功时的钩子
		handleSuccess(res) {
			this.fileIndex++;
			if (res.code == 0) {
				// this.dialogVisible = false;
			} else {
				this.$bus.$emit('closeLoading');
				this.$showCustomMessage('error', res.msg);
			}

			if (this.returnFunction != undefined) {
				this.$bus.$emit(this.returnFunction, { txt: this.buttonTxt, res: res });
			}
			// this.$parent[this.returnFunction](this.buttonTxt,res);
		},
		//文件上传失败时的钩子
		handleError(file, fileList) {
			if (this.returnFunction != undefined) {
				this.$bus.$emit(this.returnFunction, { txt: this.buttonTxt, res: res });
			}
			this.$bus.$emit('closeLoading');
			this.$showCustomMessage('error', file.name + '上传失败！');
			return;
		},
		handleRemove(file, fileList) {
			this.fileList = fileList;
		},
		//上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
		beforeUpload(file) {
			let str = file.name.split('.').pop().toLowerCase();
			this.form.showType = this.showTypeFilter(str);
			this.form.type = this.type;
			if (parseInt(this.fileSize) * 1024 * 1024 <= file.size) {
				this.$showCustomMessage('warning', `附件大小限制${this.fileSize}Mb！`);
				if (this.fileList.length == 1) {
					this.$bus.$emit('closeLoading');
				}
				return false;
			}

			var types = this.accept.split(',');
			var index = 0;
			for (var i = 0; i < types.length; i++) {
				if (file.name.indexOf(types[i]) == '-1') {
					index++;
				}
			}
			if (index == types.length) {
				this.$showCustomMessage('warning', `附件格式不支持，暂时只支持${this.accept}！`);
				this.$bus.$emit('closeLoading');
				return false;
			}
			if (this.number == '1') {
				this.$bus.$emit('openLoading');
			}
		},
		handlePreview(file) {
		},
		//文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
		handleChange(files, fileList) {
			this.fileList = fileList;
			if (parseInt(this.fileSize) * 1024 * 1024 <= files.size) {
				this.$showCustomMessage('warning', `附件大小限制${this.fileSize}Mb！`);
				return;
			}
			if (this.accept == undefined) {
				this.$refs.upload.submit();
				return true;
			}
			if (files.raw.type.indexOf('mp4') == '-1') {
				this.$refs.upload.submit();
			}
			var index = 0;
			this.menuData.forEach((element) => {
				if (element.uid == files.uid) {
					index++;
				}
			});
			if (index == 0) {
				files.index = 0;
				this.menuData.unshift(files);
			}
			this.menuData.forEach((element) => {
				if (element.uid == files.uid && element.url == undefined) {
					var url = URL.createObjectURL(files.raw);
					element.url = url;
					// this.videoUrl = url;
					this.$parent[this.values] = url;
					this.$parent.menuIndex = 0;
				}
			});

			if (this.number == '1') {
				this.fileList = [files];
				this.$refs.upload.submit();
			}
		},
		handleExceed(files, fileList) {
			this.$showCustomMessage('warning', `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
		},
		//文件上传时的钩子
		handleProgress(file, fileList) {
			// if (
			//     $(".el-loading-mask .el-loading-spinner .el-loading-list" + file.total)
			//         .length == 0
			// ) {
			//     $(".el-loading-mask .el-loading-spinner .el-loading-list").append(
			//         "<p class='el-loading-text' id='" +
			//         file.total +
			//         "'" +
			//         file.name +
			//         "正在上传</p>"
			//     );
			// } else {
			//     $(
			//         ".el-loading-mask .el-loading-spinner .el-loading-list #" + file.total
			//     ).html(file.name + "正在上传" + parseInt(file.percent) + "%");
			// }
		},
		//删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除
		beforeRemove(file, fileList) {
			// return this.$confirm("确定要移除吗?", "提示", {
			//   confirmButtonText: "删除",
			//   cancelButtonText: "取消",
			//   type: "warning",
			// })
			//   .then(() => {
			//     this.fileList.forEach((item, index) => {
			//       if (item.name == file.name) {
			//         fileList.splice(index, 1);
			//         return true;
			//       }
			//     });
			//     this.fileList = fileList;
			//   })
			//   .catch(() => {});
		},
		submit(index) {
			this.$refs.upload.submit(index);
		},
		//1.图片 2.音频 3.视频 4.文档 5.压缩文件 6.其他
		showTypeFilter(type) {
			switch (type) {
				case 'png':
				case 'jpg':
				case 'jpeg':
				case 'gif':
				case 'bmp':
					return 1;
				case 'mp3':
					return 2;
				case 'avi':
				case 'mp4':
					return 3;
				case 'txt':
				case 'doc':
				case 'docx':
				case 'xls':
				case 'xlsx':
				case 'pdf':
				case 'ppt':
					return 4;
				case 'rar':
				case 'zip':
					return 5;
				default:
					return 6;
			}
		}
	}
};
</script>

<style scoped>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
	border: 1px dashed #8c939d;
}

.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
